# -*- coding: UTF-8 -*-

from flask import Blueprint, request, render_template, url_for, session, flash, views
from werkzeug.utils import redirect
from werkzeug.security import generate_password_hash, check_password_hash

from app import db
from app.db.flow_model import User, Role, RoleMap
from app.db.work_status import TaskStatus, ProcessStatus, UserAction
from app.forms.forms import *

blue = Blueprint("user", __name__)


def init_user_blue(app):
    app.register_blueprint(blue, url_prefix="/user/")


def current_user():
    if 'account' in session:
        return User.query.filter_by(account=session['account']).first()
    else:
        return None


@blue.route('/logout/', endpoint='logout')
def logout():
    session.clear()
    return redirect(url_for('user.login'))


@blue.route('/login/', methods=['GET', 'POST'], endpoint='login')
def login():
    form = LoginForm()
    if request.method == 'GET':
        return render_template("login.html", form=form, user=None)
    else:
        if form.validate_on_submit():
            account = form.account.data.lower()
            password = form.password.data

            user = User.query.filter_by(account=account).first()
            if user :
                if not user.enabled:
                    flash('用户未启用', 'info')
                else:
                    if check_password_hash(user.password, password):
                        session['account'] = account
                        flash('登陆成功', 'ok')
                        return redirect(url_for("admin.index"))
                    else:
                        flash('密码错误', 'error')
            else:
                flash('账号不存在', 'error')
        else:
            flash('未知错误', 'error')
        return redirect(url_for("user.login"))


@blue.route('/sign/', methods=['GET', 'POST'], endpoint='sign')
def sign():
    form = SignForm()
    if request.method == 'GET':
        return render_template("sign.html", form=form, user=None)
    else:
        form = SignForm()
        account = form.account.data.lower().replace(' ', '')
        name = form.name.data
        password = form.password.data

        if form.validate_on_submit():
            u1 = User.query.filter_by(name=name).first()
            u2 = User.query.filter_by(account=account).first()
            if u1:
                flash('名称:"' + name + '"已经被使用', 'error')
                return redirect(url_for("admin.sign"))
            if u2:
                flash('账号:"' + account + '"已经被注册', 'error')
                return redirect(url_for("admin.sign"))
            try:
                user = User()
                form.populate_obj(user)
                user.password=generate_password_hash(password)
                db.session.add(user)
                db.session.commit()
                session['account'] = user.account
                flash("注册成功!", 'ok')
                return redirect(url_for("admin.index"))
            except Exception as error:
                db.session.rollback()
                flash("注册失败!%s" % str(error), 'error')
                return redirect(url_for("user.sign"))

        return redirect(url_for("user.sign"))


@blue.route('/update/<string:account>', methods=['GET', 'POST'], endpoint='update')
def update(account):
    old_user = User.query.filter_by(account=account).first()
    if request.method == 'GET':
        form = UserUpdateForm(**old_user.to_dict())
        return render_template("update_user.html", form=form, old_user=old_user)
    else:
        form = UserUpdateForm()
        name = form.name.data

        verif = User.query.filter_by(name=name).first()
        if verif and old_user.account != verif.account:
            flash('名称:"' + name + '"已经被注册', 'error')
            return render_template("update_user.html", form=form, old_user=old_user)
        form.populate_obj(old_user)
        db.session.add(old_user)
        db.session.commit()
        flash("修改成功成功!", 'ok')
        return render_template("update_user.html", form=form, old_user=old_user)


@blue.route('/enabled/<int:uid>', methods=['GET', 'POST'])
def user_enabled(uid):
    user = current_user()
    update_user = User.query.filter_by(uid=uid).first()
    name = update_user.name
    if update_user:
        update_user.enabled = not update_user.enabled
        db.session.add(update_user)
        db.session.commit()
    flash("更新成功 %s" % name, 'ok')
    return redirect(url_for("user.all", fid=1000))


@blue.route('/delete_user/<int:uid>', methods=['GET', 'POST'])
def delete_user(uid):
    del_user = User.query.filter_by(uid=uid).first()
    name = del_user.name
    # if del_user and del_user.uid:
    #     db.session.delete(del_user)
    #     db.session.commit()
    # flash("删除成功 %s" % name, 'ok')
    flash("删除功能保留中", 'ok')
    return redirect(url_for("user.all", fid=1000))


@blue.route('/create/', methods=['GET', 'POST'])
def create():
    if request.method == 'GET':
        form = UserForm()
        return render_template("create_user.html", form=form)
    if request.method == 'POST':
        form = UserForm()
        account = form.account.data.lower().replace(' ', '')
        name = form.name.data

        if form.validate_on_submit():
            u1 = User.query.filter_by(name=name).first()
            u2 = User.query.filter_by(account=account).first()
            if u1:
                flash('名称:"' + name + '"已经被使用', 'error')
                return render_template("create_user.html", form=form)
            if u2:
                flash('账号:"' + account + '"已经被注册', 'error')
                return render_template("create_user.html", form=form)
            try:
                user = User()
                form.populate_obj(user)
                db.session.add(user)
                db.session.commit()
                flash("创建成功!", 'ok')
                return redirect(url_for("user.users"))
            except Exception as error:
                db.session.rollback()
                flash("创建失败!%s" % str(error), 'error')
                return render_template("create_user.html", form=form)


@blue.route('/', methods=['GET', 'POST'], endpoint='all')
def get_users():
    form = UserForm()

    if request.method == 'GET':
        roles = Role.query.all()
        users = User.query.all()
        return render_template("users.html", users=users, form=form, roles=roles)


@blue.route('/<string:account>', methods=['GET'], endpoint='get')
def get_user(account):
    return redirect(url_for('user.update', account=account))
